package com.weijian.demo1.service;

import org.springframework.stereotype.Service;
import java.util.concurrent.*;
import java.util.Map;
import java.util.HashMap;

@Service
public class DocumentDebounceService {
    
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    private final Map<Long, ScheduledFuture<?>> pendingSaves = new ConcurrentHashMap<>();
    private final DocumentMemoryService documentMemoryService;
    private final DocumentService documentService;
    
    public DocumentDebounceService(DocumentMemoryService documentMemoryService, DocumentService documentService) {
        this.documentMemoryService = documentMemoryService;
        this.documentService = documentService;
    }
    
    /**
     * 防抖保存：用户停止输入2秒后保存到数据库
     */
    public void debounceSave(Long documentId, Long userId) {
        // 取消之前的定时任务
        ScheduledFuture<?> previousTask = pendingSaves.get(documentId);
        if (previousTask != null) {
            previousTask.cancel(false);
        }
        
        // 创建新的2秒后保存任务
        ScheduledFuture<?> newTask = scheduler.schedule(() -> {
            String content = documentMemoryService.getFromMemory(documentId);
            if (content != null) {
                // 异步保存到数据库
                documentService.updateDocumentContent(documentId, content, userId);
                System.out.println("✅ 防抖保存成功：文档 " + documentId + " 已保存到数据库");
            }
            pendingSaves.remove(documentId);
        }, 2, TimeUnit.SECONDS);
        
        pendingSaves.put(documentId, newTask);
    }
    
    /**
     * 立即保存（用户手动点击保存按钮时）
     */
    public void immediateSave(Long documentId, Long userId) {
        // 取消防抖任务
        ScheduledFuture<?> task = pendingSaves.get(documentId);
        if (task != null) {
            task.cancel(false);
            pendingSaves.remove(documentId);
        }
        
        // 立即保存
        String content = documentMemoryService.getFromMemory(documentId);
        if (content != null) {
            documentService.updateDocumentContent(documentId, content, userId);
            System.out.println("⚡ 立即保存成功：文档 " + documentId + " 已保存到数据库");
        }
    }
    
    /**
     * 关闭文档时清理资源
     */
    public void cleanup(Long documentId) {
        ScheduledFuture<?> task = pendingSaves.get(documentId);
        if (task != null) {
            task.cancel(false);
            pendingSaves.remove(documentId);
        }
        documentMemoryService.clearFromMemory(documentId);
    }
}